home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-rdflib / rdflib / TextIndex.py < prev    next >
Encoding:
Python Source  |  2007-04-04  |  11.7 KB  |  308 lines

  1. import logging
  2. _logger = logging.getLogger(__name__)
  3.  
  4. import re #, stopdict
  5.  
  6. def get_stopdict():
  7.     """Return a dictionary of stopwords."""
  8.     return _dict
  9.  
  10. _words = [
  11.     "a", "and", "are", "as", "at", "be", "but", "by",
  12.     "for", "if", "in", "into", "is", "it",
  13.     "no", "not", "of", "on", "or", "such",
  14.     "that", "the", "their", "then", "there", "these",
  15.     "they", "this", "to", "was", "will", "with"
  16. ]
  17.  
  18. _dict = {}
  19. for w in _words:
  20.     _dict[w] = None
  21.  
  22. word_pattern = re.compile(r"(?u)\w+")
  23. has_stop = get_stopdict().has_key
  24.  
  25. def splitter(s):
  26.     return word_pattern.findall(s)
  27.  
  28. def stopper(s):
  29.     return [w.lower() for w in s if not has_stop(w)]
  30.  
  31.  
  32. try:
  33.     from hashlib import md5
  34. except ImportError:
  35.     from md5 import md5    
  36.  
  37. from rdflib.store.IOMemory import IOMemory
  38. from rdflib import URIRef, Literal, RDF, BNode
  39. from rdflib.Namespace import NamespaceDict as Namespace
  40. from rdflib.Graph import ConjunctiveGraph
  41. from rdflib.store import TripleAddedEvent, TripleRemovedEvent
  42.  
  43.  
  44. class TextIndex(ConjunctiveGraph):
  45.     """
  46.     An rdflib graph event handler than indexes text literals that are
  47.     added to a another graph.
  48.  
  49.     This class lets you 'search' the text literals in an RDF graph.
  50.     Typically in RDF to search for a substring in an RDF graph you
  51.     would have to 'brute force' search every literal string looking
  52.     for your substring.
  53.  
  54.     Instead, this index stores the words in literals into another
  55.     graph whose structure makes searching for terms much less
  56.     expensive.  It does this by chopping up the literals into words,
  57.     removing very common words (currently only in English) and then
  58.     adding each of those words into an RDF graph that describes the
  59.     statements in the original graph that the word came from.
  60.  
  61.     First, let's create a graph that will transmit events and a text
  62.     index that will receive those events, and then subscribe the text
  63.     index to the event graph:
  64.  
  65.       >>> e = ConjunctiveGraph()
  66.       >>> t = TextIndex()
  67.       >>> t.subscribe_to(e)
  68.  
  69.     When triples are added to the event graph (e) events will be fired
  70.     that trigger event handlers in subscribers.  In this case our only
  71.     subscriber is a text index and its action is to index triples that
  72.     contain literal RDF objects.  Here are 3 such triples:
  73.  
  74.       >>> e.add((URIRef('a'), URIRef('title'), Literal('one two three')))
  75.       >>> e.add((URIRef('b'), URIRef('title'), Literal('two three four')))
  76.       >>> e.add((URIRef('c'), URIRef('title'), Literal('three four five')))
  77.  
  78.     Of the three literal objects that were added, they all contain
  79.     five unique terms.  These terms can be queried directly from the
  80.     text index:
  81.     
  82.       >>> t.term_strings() ==  set(['four', 'five', 'three', 'two', 'one'])
  83.       True
  84.  
  85.     Now we can search for statement that contain certain terms.  Let's
  86.     search for 'one' which occurs in only one of the literals
  87.     provided, 'a'.  This can be queried for:
  88.  
  89.       >>> t.search('one')
  90.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None)])
  91.  
  92.     'one' and 'five' only occur in one statement each, 'two' and
  93.     'four' occur in two, and 'three' occurs in three statements:
  94.  
  95.       >>> len(list(t.search('one')))
  96.       1
  97.       >>> len(list(t.search('two')))
  98.       2
  99.       >>> len(list(t.search('three')))
  100.       3
  101.       >>> len(list(t.search('four')))
  102.       2
  103.       >>> len(list(t.search('five')))
  104.       1
  105.  
  106.     Lets add some more statements with different predicates.
  107.  
  108.       >>> e.add((URIRef('a'), URIRef('creator'), Literal('michel')))
  109.       >>> e.add((URIRef('b'), URIRef('creator'), Literal('Atilla the one Hun')))
  110.       >>> e.add((URIRef('c'), URIRef('creator'), Literal('michel')))
  111.       >>> e.add((URIRef('d'), URIRef('creator'), Literal('Hun Mung two')))
  112.  
  113.     Now 'one' occurs in two statements:
  114.  
  115.       >>> assert len(list(t.search('one'))) == 2
  116.  
  117.     And 'two' occurs in three statements, here they are:
  118.  
  119.       >>> t.search('two')
  120.       set([(rdflib.URIRef('d'), rdflib.URIRef('creator'), None), (rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  121.  
  122.     The predicates that are searched can be restricted by provding an
  123.     argument to 'search()':
  124.  
  125.       >>> t.search('two', URIRef('creator'))
  126.       set([(rdflib.URIRef('d'), rdflib.URIRef('creator'), None)])
  127.  
  128.       >>> t.search('two', URIRef(u'title'))
  129.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  130.  
  131.     You can search for more than one term by simply including it in
  132.     the query:
  133.     
  134.       >>> t.search('two three', URIRef(u'title'))
  135.       set([(rdflib.URIRef('c'), rdflib.URIRef('title'), None), (rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  136.  
  137.     The above query returns all the statements that contain 'two' OR
  138.     'three'.  For the documents that contain 'two' AND 'three', do an
  139.     intersection of two queries:
  140.  
  141.       >>> t.search('two', URIRef(u'title')).intersection(t.search(u'three', URIRef(u'title')))
  142.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  143.  
  144.     Intersection two queries like this is probably not the most
  145.     efficient way to do it, but for reasonable data sets this isn't a
  146.     problem.  Larger data sets will want to query the graph with
  147.     sparql or something else more efficient.
  148.  
  149.     In all the above queries, the object of each statement was always
  150.     'None'.  This is because the index graph does not store the object
  151.     data, that would make it very large, and besides the data is
  152.     available in the original data graph.  For convenience, a method
  153.     is provides to 'link' an index graph to a data graph.  This allows
  154.     the index to also provide object data in query results.
  155.  
  156.       >>> t.link_to(e)
  157.       >>> set([str(i[2]) for i in t.search('two', URIRef(u'title')).intersection(t.search(u'three', URIRef(u'title')))]) ==  set(['two three four', 'one two three'])
  158.       True
  159.  
  160.     You can remove the link by assigning None:
  161.  
  162.       >>> t.link_to(None)
  163.  
  164.     Unindexing means to remove statments from the index graph that
  165.     corespond to a statement in the data graph.  Note that while it is
  166.     possible to remove the index information of the occurances of
  167.     terms in statements, it is not possible to remove the terms
  168.     themselves, terms are 'absolute' and are never removed from the
  169.     index graph.  This is not a problem since languages have finite
  170.     terms:
  171.  
  172.       >>> e.remove((URIRef('a'), URIRef('creator'), Literal('michel')))
  173.       >>> e.remove((URIRef('b'), URIRef('creator'), Literal('Atilla the one Hun')))
  174.       >>> e.remove((URIRef('c'), URIRef('creator'), Literal('michel')))
  175.       >>> e.remove((URIRef('d'), URIRef('creator'), Literal('Hun Mung two')))
  176.  
  177.     Now 'one' only occurs in one statement:
  178.  
  179.       >>> assert len(list(t.search('one'))) == 1
  180.  
  181.     And 'two' only occurs in two statements, here they are:
  182.  
  183.       >>> t.search('two')
  184.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  185.  
  186.     The predicates that are searched can be restricted by provding an
  187.     argument to 'search()':
  188.  
  189.       >>> t.search('two', URIRef(u'creator'))
  190.       set([])
  191.  
  192.       >>> t.search('two', URIRef(u'title'))
  193.       set([(rdflib.URIRef('a'), rdflib.URIRef('title'), None), (rdflib.URIRef('b'), rdflib.URIRef('title'), None)])
  194.  
  195.     """
  196.  
  197.     linked_data = None
  198.  
  199.     text_index = Namespace('http://rdflib.net/text_index#')
  200.     term = Namespace('http://rdflib.net/text_index#')["term"]
  201.     termin = Namespace('http://rdflib.net/text_index#')["termin"]
  202.  
  203.     def __init__(self, store='default'):
  204.         super(TextIndex, self).__init__(store)
  205.  
  206.     def add_handler(self, event):
  207.         if type(event.triple[2]) is Literal:
  208.             self.index(event.triple)
  209.         
  210.     def remove_handler(self, event):
  211.         if type(event.triple[2]) is Literal:
  212.             self.unindex(event.triple)
  213.  
  214.     def index(self, (s, p, o)):
  215.         # this code is tricky so it's annotated.  unindex is the reverse of this method.
  216.                 
  217.         if type(o) is Literal:                            # first, only index statements that have a literal object
  218.             for word in stopper(splitter(o)):             # split the literal and remove any stopwords
  219.                 word = Literal(word)                      # create a new literal for each word in the object
  220.                 
  221.                 # if that word already exists in the statement
  222.                 # loop over each context the term occurs in
  223.                 if self.value(predicate=self.term, object=word, any=True): 
  224.                     for t in set(self.triples((None, self.term, word))):
  225.                         t = t[0]
  226.                         # if the graph does not contain an occurance of the term in the statement's subject
  227.                         # then add it
  228.                         if not (t, self.termin, s) in self:
  229.                             self.add((t, self.termin, s))
  230.  
  231.                         # ditto for the predicate
  232.                         if not (p, t, s) in self:
  233.                             self.add((p, t, s))
  234.  
  235.                 else: # if the term does not exist in the graph, add it, and the references to the statement.
  236.                     # t gets used as a predicate, create identifier accordingly (AKA can't be a BNode)
  237.                     h = md5(word); h.update(s); h.update(p)
  238.                     t = self.text_index["term_%s" % h.hexdigest()]
  239.                     self.add((t, self.term, word))
  240.                     self.add((t, self.termin, s))
  241.                     self.add((p, t, s))
  242.         
  243.     def unindex(self, (s, p, o)):
  244.         if type(o) is Literal:
  245.             for word in stopper(splitter(o)):
  246.                 word = Literal(word)
  247.                 if self.value(predicate=self.term, object=word, any=True):
  248.                     for t in self.triples((None, self.term, word)):
  249.                         t = t[0]
  250.                         if (t, self.termin, s) in self:
  251.                             self.remove((t, self.termin, s))
  252.                         if (p, t, s) in self:
  253.                             self.remove((p, t, s))
  254.  
  255.     def terms(self):
  256.         """ Returns a generator that yields all of the term literals in the graph. """
  257.         return set(self.objects(None, self.term))
  258.  
  259.     def term_strings(self):
  260.         """ Return a list of term strings. """
  261.         return set([str(i) for i in self.terms()])
  262.  
  263.     def search(self, terms, predicate=None):
  264.         """ Returns a set of all the statements the term occurs in. """
  265.         if predicate and not isinstance(predicate, URIRef):
  266.             _logger.warning("predicate is not a URIRef")
  267.             predicate = URIRef(predicate)
  268.         results = set()
  269.         terms = [Literal(term) for term in stopper(splitter(terms))]    
  270.  
  271.         for term in terms:
  272.             for t in self.triples((None, self.term, term)):
  273.                 for o in self.objects(t[0], self.termin):
  274.                     for p in self.triples((predicate, t[0], o)):
  275.                         if self.linked_data is None:
  276.                             results.add((o, p[0], None))
  277.                         else:
  278.                             results.add((o, p[0], self.linked_data.value(o, p[0])))
  279.         return results
  280.  
  281.     def index_graph(self, graph):
  282.         """
  283.         Index a whole graph.  Must be a conjunctive graph.
  284.         """
  285.         for t in graph.triples((None,None,None)):
  286.             self.index(t)
  287.  
  288.     def link_to(self, graph):
  289.         """
  290.         Link to a graph
  291.         """
  292.         self.linked_data = graph
  293.  
  294.     def subscribe_to(self, graph):
  295.         """
  296.         Subscribe this index to a graph.
  297.         """
  298.         graph.store.dispatcher.subscribe(TripleAddedEvent, self.add_handler)
  299.         graph.store.dispatcher.subscribe(TripleRemovedEvent, self.remove_handler)
  300.  
  301.  
  302. def test():
  303.     import doctest
  304.     doctest.testmod()
  305.  
  306. if __name__ == '__main__':
  307.     test()
  308.